package com.anzuo.app.ui.main

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.anzuo.app.data.model.Item
import com.anzuo.app.databinding.ItemHomeBinding

/**
 * HomeAdapter - 首页RecyclerView适配器
 * 使用ListAdapter和DiffUtil实现高效的列表更新
 * 
 * @author AnZuo
 * @date 2024
 */
class HomeAdapter : ListAdapter<Item, HomeAdapter.ViewHolder>(ItemDiffCallback()) {

    /**
     * ViewHolder - 持有视图引用
     */
    class ViewHolder(
        private val binding: ItemHomeBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        /**
         * 绑定数据到视图
         */
        fun bind(item: Item) {
            binding.apply {
                // 设置数据到视图
                titleText.text = item.title
                descriptionText.text = item.description
                
                // 设置点击事件
                root.setOnClickListener {
                    // 处理点击事件
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemHomeBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    /**
     * DiffUtil回调 - 用于比较列表项是否相同
     */
    private class ItemDiffCallback : DiffUtil.ItemCallback<Item>() {
        override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
            return oldItem == newItem
        }
    }
}

